package com.ysxsoft.wdg;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.support.multidex.MultiDexApplication;
import android.util.Log;

import com.ali.auth.third.core.MemberSDK;
import com.alibaba.baichuan.android.trade.AlibcTradeSDK;
import com.alibaba.baichuan.android.trade.callback.AlibcTradeInitCallback;
import com.kepler.jd.Listener.AsyncInitListener;
import com.kepler.jd.login.KeplerApiManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreater;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.socks.library.KLog;
import com.tencent.smtt.sdk.QbSdk;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.widget.SmartRefreshHeader;

import java.util.HashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;

public class MyApplication extends MultiDexApplication {

    static {//static 代码段可以防止内存泄露
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.colorPrimary,R.color.line_color);//全局设置主题颜色
                return new SmartRefreshHeader(context);
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new BallPulseFooter(context).setSpinnerStyle(SpinnerStyle.Translate);
            }
        });
    }

    public static final String WXAppId = "wx42819c2aa5755f32";
    public static final String WX_SCRECT = "94d1d732e02fde2460732406a5097463";

    public static final String QQAppId = "1107860281";
    public static final String QQ_SCRECT = "TDl3qgt7fkYqe3Yk";

    public static final String UMENG_KEY = "5bd6da4eb465f5864200024c";

    //友盟
    static {
        //开放平台对应的AppId和Appkey
        PlatformConfig.setWeixin(WXAppId, WX_SCRECT);
        //第三个参数是回调地址
        PlatformConfig.setQQZone(QQAppId, QQ_SCRECT);
        //        PlatformConfig.setSinaWeibo(SINA_AppId,SINA_SCRECT,"");
    }


    @SuppressLint("StaticFieldLeak")
    private static Context context;
    @SuppressLint("StaticFieldLeak")
    private static MyApplication instance;

    private Set<BaseActivity> mActivities;

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        instance = this;
        JPushInterface.init(this);
        ToastUtils.init(this);

        KLog.init(BuildConfig.DEBUG);

        initX5();
        initAlibc();

        initUmeng();
        initJD();
    }

    private void initJD() {
        KeplerApiManager.setD(true);
        KeplerApiManager
                .asyncInitSdk(this, "56aecdf5b7be4422b5a69e1f281ba16b",
                "9e5223bb5908455da2dc8a1c6b43d519", new AsyncInitListener() {
                    @Override
                    public void onSuccess() {
                        KLog.e("JD_Kepler", "Kepler asyncInitSdk onSuccess ");
                    }

                    @Override
                    public void onFailure() {
                        KLog.e("JD_Kepler", "Kepler asyncInitSdk 授权失败，请检查 lib 工程资源引用；包名,签名证书是否和注册一致");
                    }
                });
    }

    private void initX5(){
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                Log.d("app", " onViewInitFinished is " + arg0);
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(),  cb);
    }

    private void initUmeng() {
        /**
         * 初始化common库
         * 参数1:上下文，不能为空
         * 参数2:【友盟+】 AppKey
         * 参数3:【友盟+】 Channel
         * 参数4:设备类型，UMConfigure.DEVICE_TYPE_PHONE为手机、UMConfigure.DEVICE_TYPE_BOX为盒子，默认为手机
         * 参数5:Push推送业务的secret
         */
        UMConfigure.init(this,UMENG_KEY
                , "umeng", UMConfigure.DEVICE_TYPE_PHONE, "");
        //方便定位错误，具体错误检查方式可以查看http://dev.umeng.com/social/android/quick-integration的报错必看
        UMConfigure.setLogEnabled(BuildConfig.DEBUG);
        UMShareAPI.get(this);
    }

    private void initAlibc() {
        MemberSDK.turnOnDebug();
        AlibcTradeSDK.asyncInit(this, new AlibcTradeInitCallback() {
            @Override
            public void onSuccess() {
                //初始化成功，设置相关的全局配置参数
                KLog.e("Alibc=="+"成功");
            }

            @Override
            public void onFailure(int code, String msg) {
                //初始化失败，可以根据code和msg判断失败原因，详情参见错误说明
                KLog.e("Alibc=="+"失败"+code);
            }
        });
    }


    public static Context getContext() {
        return context;
    }

    public static MyApplication getInstance() {
        return instance;
    }

    /**
     * 添加activity
     */
    public void addActivity(BaseActivity act) {
        if (mActivities == null) {
            mActivities = new HashSet<>();
        }
        mActivities.add(act);
    }

    /**
     * 移除activity
     */
    public void removeActivity(BaseActivity act) {
        if (mActivities != null) {
            mActivities.remove(act);
        }
    }

    /**
     * 退出app
     */
    public void exitApp() {
        if (mActivities != null) {
            for (Activity act : mActivities) {
                act.finish();
            }
        }
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }
}
